#pragma once
#include <vector>
#include <pthread.h>
#include <semaphore.h>
#include<ctime>
#include<functional>
#include<string>
#define RING_CAP 10
template <class T>
class RingQueue
{
public:
    RingQueue(int cap = RING_CAP) : _ring(cap),
                                    _cap(cap)
    {
        _c_step = _p_step = 0;
        sem_init(&_data_sem, 0, 0);
        sem_init(&_space_sem, 0, RING_CAP);
        pthread_mutex_init(&_c_mutex, nullptr);
        pthread_mutex_init(&_p_mutex, nullptr);
    }
    ~RingQueue()
    {
        sem_destroy(&_data_sem);
        sem_destroy(&_space_sem);
        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }
    void push(const T &in)
    {
        P(_space_sem);
        lock(_p_mutex);
        _ring[_p_step++]=in;
        _p_step%=_cap;
        unlock(_p_mutex);
        V(_data_sem);
    }
    void pop(T &out)
    {
        P(_data_sem);
        lock(_c_mutex);
        out=_ring[_c_step++];
        _c_step%=_cap;
        unlock(_c_mutex);
        V(_space_sem);
    }

private:
    void P(sem_t &s)
    {
        sem_wait(&s);
    }
    void V(sem_t &s)
    {
        sem_post(&s);
    }
    void lock(pthread_mutex_t& m)
    {
        pthread_mutex_lock(&m);
    }
    void unlock(pthread_mutex_t& m)
    {
        pthread_mutex_unlock(&m);
    }
private:
    std::vector<T> _ring;
    int _cap; // 环形队列大小
    sem_t _data_sem;//消费者只关心有没有数据
    sem_t _space_sem;//生产者只关心有没有空间
    int _c_step; // 消费位置
    int _p_step; // 生产位置

    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};


class CalTask
{
    typedef std::function<int(int,int,char)> func_t;
public:
    //默认构造
    CalTask()
    {}
    //构造函数
    CalTask(int a, int b, char op, func_t func)
        :_a(a)
        ,_b(b)
        ,_op(op)
        ,_func(func)
    {}
 
    //仿函数
std::string operator()()
    {
        int result = _func(_a, _b, _op);
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%d %c %d = %d\n", _a, _op, _b, result);
        std::string s(buffer);
        return s;
    }
 
    //显示任务
    std::string show_task()
    {
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%d %c %d = ?\n", _a, _op, _b);
        std::string s(buffer);
        return s;
    }
private:
    func_t _func;
    int _a;
    int _b;
    char _op;
};
